package org.tinygroup.tinyscript.springmvc;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;
import org.tinygroup.context.Context;
import org.tinygroup.tinyscript.ScriptEngine;
import org.tinygroup.tinyscript.ScriptEngineFactory;
import org.tinygroup.tinyscript.config.ParameterConfig;
import org.tinygroup.tinyscript.mvc.ControllerContext;
import org.tinygroup.tinyscript.mvc.ResponseWrapper;
import org.tinygroup.tinyscript.mvc.ScriptController;
import org.tinygroup.tinyscript.mvc.context.DefaultControllerContext;

@SuppressWarnings("rawtypes")
public class ScriptControllerHandlerAdapter implements HandlerAdapter{

    private ScriptEngine scriptEngine;
    
	private ResponseWrapper responseWrapper;
	
	protected  ScriptEngine getScriptEngine() throws Exception{
		 if(scriptEngine==null){
			scriptEngine = ScriptEngineFactory.createByBean();
		 }
		 return scriptEngine;
	}

	public ResponseWrapper getResponseWrapper() {
		return responseWrapper;
	}

	public void setResponseWrapper(ResponseWrapper responseWrapper) {
		this.responseWrapper = responseWrapper;
	}

	public boolean supports(Object handler) {
		return handler instanceof ScriptController;
	}

	public ModelAndView handle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		ScriptController controller = (ScriptController) handler;
		ControllerContext context = new DefaultControllerContext(request,response,controller);
		Object value = executeService(context,controller);
		return (ModelAndView) responseWrapper.wrap(context, value);
	}
	
	protected Object executeService(Context context,ScriptController controller) throws Exception {
		List<ParameterConfig> list = controller.getFunctionConfig().getParameters();
		Object[] parameters = new Object[list==null?0:list.size()];
		if(list!=null){
		   for(int i=0;i<list.size();i++){
			   parameters[i] = context.get(list.get(i).getName());
		   }
		}
		return getScriptEngine().execute(controller.getScriptClassName(), controller.getFunctionName(), parameters);
	}

	public long getLastModified(HttpServletRequest request, Object handler) {
		return -1;
	}

}
